<?php
/**
 * Description
 * User: duanwenjie
 * Date: 2019/5/9
 * Time: 11:59 AM
 */

namespace app\index\service;
use app\common\model\ToolModel;
use think\Db;
use think\Exception;

class CompanyService
{
    static public function getCompanyList($param, $is_download = false)
    {
        try{
            $where = "where 1 = 1 ";
            $pageNumber = isset($param['page']) ? $param['page'] : 1;
            $pageData = isset($param['limit']) ? $param['limit'] : 20;
            $company_name = isset($param['company_name']) ? $param['company_name'] : '';  //公司名称
            $company_id = isset($param['id']) ? $param['id'] : '';  //公司代码
            $country_name = isset($param['country_name']) ? $param['country_name'] : '';  //所属国家
            $status = isset($param['status']) ? $param['status'] : '';  //状态
            $type = isset($param['type']) ? $param['type'] : '';  //公司类型
            $offset = ($pageNumber - 1) * $pageData;
            $limit = " LIMIT $offset,$pageData";

            if (!empty($company_name)) {
                $company_name = trim($company_name);
                $where .= " AND company_name = '{$company_name}'";
            }
            if (!empty($company_id)) {
                $company_id = trim($company_id);
                $where .= " AND id = {$company_id}";
            }
            if (!empty($country_name)) {
                $country_name = trim($country_name);
                $where .= " AND base_country_name = '{$country_name}'";
            }
            if (!empty($status)) {
                $where .= " AND status = {$status}";
            }
            if (!empty($type)) {
                $where .= " AND type = {$type}";
            }

            $sqlCount = "SELECT COUNT(id) num FROM base_company {$where}";
            $countArr = ToolModel::queryData($sqlCount);
            if (empty($countArr) || $countArr[0]['num'] == 0) {
                return array('total' => 0, 'list' => array());
            }
            $fileds = 'id,company_name,base_country_name,address,
                      case type when 1 then "贸易公司" when 2 then "零售公司" when 3 then "贸易及零售公司" when 4 then "加盟及零售公司"
                      when 5 then "供应商" end type_name,case status when 1 then "启用" when -1 then "禁用" end status_name,type,status,
                      sale_proportion,operator,update_time';

            $sql = "SELECT {$fileds} FROM base_company {$where} ORDER BY id DESC {$limit}";
            if ($is_download) $sql = "SELECT {$fileds} FROM base_company {$where} ORDER BY id DESC ";
            $list = ToolModel::queryData($sql);
            $data = array();
            $data['total'] = intval($countArr[0]['num']);
            foreach ($list as &$v){
                if ($v['sale_proportion'] == "0.0000"){
                    $v['sale_proportion'] = "";
                }else{
                    $v['sale_proportion'] = ($v['sale_proportion']*100)."%"; // 转换销售加成比例数据
                }
            }
            $data['list'] = $list;

            return $data;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 校验新增/编辑数据
     * @param $params
     * @param string $id
     * @return array
     * @throws Exception
     * @author duanwenjie
     */
    static public function checkData($params, $id = "")
    {
        try{
            $base_country_name = $params['base_country_name'];
            $company_name = $params['company_name'];
            /*校验国家*/
            $res = Db::name('base_country')->where('name_zh', '=', $base_country_name)->find();
            if (empty($res)) returnJson(200, "操作失败！国家：({$base_country_name})不存在");
            if (empty($id)){
                /*新增需校验公司*/
                $res2 = Db::name('base_company')->where('company_name', '=', $company_name)->find();
                if (!empty($res2)) returnJson(200, "操作失败！公司：({$company_name})已存在");
                self::chenckCountry($base_country_name,$params['type'],true);
            }else{
                $res_ = Db::name('base_company')->where('id', '=', $id)->find();
                if (isset($res_['company_name']) && $res_['company_name'] != $params['company_name']){
                    /*编辑的公司名称发生改变需校验公司*/
                    $res3 = Db::name('base_company')->where('company_name', '=', $company_name)->find();
                    if (!empty($res3)) returnJson(200, "操作失败！公司：({$company_name})已存在");
                }
                if (isset($res_['type']) && $res_['type'] != $params['type']){
                    self::chenckCountry($base_country_name,$params['type']);
                }
            }
            $base_country_id = $res['id'];
            $base_country_name = $res['name_zh'];
            $data = array("base_country_id" => $base_country_id,"base_country_name" => $base_country_name);

            return $data;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 公司更新联动更新店铺相关数据
     * @param $base_company_id
     * @param $base_country_id
     * @param $base_country_name
     * @author duanwenjie
     */
    static public function updateShop($base_company_id, $base_country_id, $base_country_name)
    {
        $res = ToolModel::updateData(array("base_company_id" => $base_company_id),array("base_country_id" => $base_country_id,"base_country_name" => $base_country_name),'base_shop');

    }


    /**
     * 检验国家、公司贸易类型关系
     * 规则：如果已选择为type=3：贸易及零售公司，则当前国家不能再创建type=1或者type=2的公司，反之
     *      如果选择type=1，则不能创建type=3，选择type=2，也不能创建type=3
     * @param $base_country_name
     * @param $type
     * @param bool $is_create
     * @author duanwenjie
     */
    static public function chenckCountry($base_country_name, $type, $is_create = false)
    {
        if ($type == 1){
            /*编辑的type改变，且=1（贸易公司）需要校验该国家下是否有贸易公司或贸易及零售公司存在*/
            $sql1 = "SELECT * FROM (SELECT * FROM `base_company` WHERE `type` = '1' OR `type` = '3') as A WHERE A.`base_country_name` = '{$base_country_name}'";
            $res1 = Db::query($sql1);
            if (!empty($res1) && count($res1) >= 1) returnJson(200, "操作失败！国家：({$base_country_name})已存在贸易公司或贸易及零售公司");
        }elseif ($type == 2){
            /*编辑的type改变，且=2（零售公司）需要校验该国家下是否零售公司或贸易及零售公司存在*/
            $sql2 = "SELECT * FROM (SELECT * FROM `base_company` WHERE `type` = '2' OR `type` = '3') as A WHERE A.`base_country_name` = '{$base_country_name}'";
            $res2 = Db::query($sql2);
            if (!empty($res2) && count($res2) >= 1) returnJson(200, "操作失败！国家：({$base_country_name})已存在零售公司或贸易及零售公司");
        }elseif ($type == 3){
            /*编辑的type改变，且=3（贸易及零售公司）需要校验该国家下是否有贸易公司和零售公司存在*/
            if ($is_create){
                $sql3 = "SELECT * FROM (SELECT * FROM `base_company` WHERE `type` = '1' OR `type` = '2' OR `type` = '3') as A WHERE A.`base_country_name` = '{$base_country_name}'";
                $msg = "操作失败！国家：({$base_country_name})已存在贸易公司或零售公司或贸易及零售公司";
            }else{
                $sql3 = "SELECT * FROM (SELECT * FROM `base_company` WHERE `type` = '1' OR `type` = '2') as A WHERE A.`base_country_name` = '{$base_country_name}'";
                $msg = "操作失败！国家：({$base_country_name})已存在贸易公司或零售公司";
            }
            $res3 = Db::query($sql3);
            if (!empty($res3) && count($res3) >= 1) returnJson(200, $msg);
        }
    }

}